package com.searchengine.config;

import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 进程监控类
 * 用于监控系统进程状态和资源使用情况
 */
@Component
public class ProcessMonitor {

    private static final Logger logger = Logger.getLogger(ProcessMonitor.class.getName());
    
    /**
     * 构造函数
     * 初始化进程监控器
     */
    public ProcessMonitor() {
        logger.info("ProcessMonitor constructor initialized");
        // 初始化监控相关配置
        initializeMonitoring();
    }
    
    /**
     * 初始化监控配置
     */
    private void initializeMonitoring() {
        try {
            // 获取当前JVM进程信息
            ProcessHandle currentProcess = ProcessHandle.current();
            logger.info("Monitoring process: " + currentProcess.pid());
            
            // 记录系统信息
            logger.info("System properties: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
            
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Failed to initialize process monitoring", e);
        }
    }
    
    /**
     * 获取当前系统负载信息
     * @return 系统负载信息
     */
    public String getSystemLoad() {
        try {
            OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
            double cpuLoad = osBean.getSystemCpuLoad();
            long totalMemory = osBean.getTotalPhysicalMemorySize();
            long freeMemory = osBean.getFreePhysicalMemorySize();
            long usedMemory = totalMemory - freeMemory;
            return String.format("CPU load: %.2f, Memory used: %d MB", cpuLoad, usedMemory / (1024 * 1024));
        } catch (Exception e) {
            logger.log(Level.WARNING, "Failed to get system load", e);
            return "Unknown load";
        }
    }
    
    /**
     * 监控应用资源使用情况
     */
    public void monitorResources() {
        Runtime runtime = Runtime.getRuntime();
        long memoryUsed = runtime.totalMemory() - runtime.freeMemory();
        logger.info("Memory used: " + (memoryUsed / (1024 * 1024)) + " MB");
    }
    
    /**
     * 优雅关闭监控器
     */
    public void shutdown() {
        logger.info("ProcessMonitor shutting down");
        // 清理监控资源
    }
}
